Utility.php

<?php

namespace Phad;

trait Utility {

    /**
     * Generate an sql CREATE TABLE statement from a phad item containing a form.
     *
     * @param $form_item the form-item to scan & use it's inputs to form a CREATE TABLE sql statement
     *
     * @return string sql CREATE TABLE statement
     */
    function generate_create_sql(string $form_item): string {
        $phad = $this;
        $item = $phad->item($form_item);
        $info = $item->info();
        if (!is_object($info)||!isset($info->properties)){
            throw new \Exception("'$form_item' does not appear to be a phad item or does not have properties.");
        }
        $properties = $info->properties;
        // print_r($properties);
        $table = strtolower($info->name);
        $statement = "CREATE TABLE `$table` (\n    ";
        $did_first = false;
        foreach ($properties as $name=>$details){
            $col_str = $this->sql_create_col($name, $details);
            if ($did_first)$statement .=",\n    ";
            $statement .= $col_str;
            $did_first = true;
        }

        $statement .= "\n);";

        return $statement;
    }



    /**
     * Generate sql for create an individual column from node properties array
     *
     * @param $column_name the name of the column to make
     * @param $dom_input the array of attributes and info about the html input
     * @return a string like `name` VARCHAR(256)
     */
    public function sql_create_col(string $column_name, array $dom_input){
        $col = "`$column_name`";
        if ($dom_input['tagName']=='textarea')return "$col TEXT";


        if ($dom_input['tagName']=='select'){
            $type = "ENUM('"
                .implode("','", $dom_input['options'])
                ."')";
            return "$col $type";
        }


        if ($dom_input['tagName']!='input')throw new \Exception("Cannot handle tagName '".$dom_input['tagName']."'");

        $type = $dom_input['type'];
        if ($type=='checkbox')return "$col TINYINT";
        else if ($type=='hidden' && $column_name=='id')return "$col int PRIMARY KEY AUTO_INCREMENT";
        else if ($type=='text'){
            $len = 0;
            if (isset($dom_input['maxlength']))$len = (int)$dom_input['maxlength'];
            if ($len < 256)$len = 256;
            return "$col VARCHAR($len)";
        } else if ($type=='email'){
            return "$col VARCHAR(256)";
        } else if ($type=='file'){
            return "$col VARCHAR(256)";
        } else if ($type=='datetime-local'){
            return "$col DATETIME";
        } else if ($type=='time'){
            return "$col TIME";
        }




        throw new \Exception("Cannot handle input type '$type'");
    }


}